module(...,package.seeall)
import "android.graphics.Color"

formatCache={}

function toBaseHex(color)
  if formatCache[color] then
    return formatCache[color]
   else
    local hex=string.upper(Integer.toHexString(color))
    formatCache[color]=hex
    return hex
  end
end

function toHexColor(color)
  return "#"..toBaseHex(color)
end

function toHex(color)
  local base
  base=toBaseHex(color)
  if string.len(base)==6 then
    base="FF"..base
  end
  return "0x"..base
end
function toRGB(color)
  return ("%s,%s,%s,%s"):format(Color.alpha(color),Color.red(color),Color.green(color),Color.blue(color))
end


function toNumberFromHexColor(color)
  if #color==7 or #color==9 then
    return Color.parseColor(color)
   else
    return 0
  end
end

function toNumberFromRGB(color)
  local result
  result="#"
  for item in (color..","):gmatch("(.-),") do
    local hex=Integer.toHexString(tonumber(item))
    if #hex==1 then
      result=result.."0"..hex
     else
      result=result..hex
    end
  end
  return Color.parseColor(result)
end


function smartToNumber(color)
  local _,result=pcall(function()
    local result
    if color:find"#"==1 then
      result=toNumberFromHexColor(color)
     elseif tonumber("0x"..color) then
      result=toNumberFromHexColor("#"..color)
     elseif tonumber(color) then
      result=tonumber(color)
     elseif color:find(",") then
      result=toNumberFromRGB(color)
    end
    return result
  end)
  if tonumber(result) then
    return result
   else
    return "不能解析该颜色"
  end
end